package com.ease.common.enums;

/**
 * 
 * @author nathanleewei
 * 
 */
public class EnumUtil {

	public final static <T extends ValuableEnum> T get(Class<T> enumClass, short value, T defaultValue) {
		for (T e : enumClass.getEnumConstants()) {
			if (e.getValue() == value) {
				return e;
			}
		}
		return defaultValue;
	}

	public final static <T extends ValuableEnum> T get(Class<T> enumClass, short value) {
		return get(enumClass, value, null);
	}

	public final static <T extends TextualEnum> T getByText(Class<T> enumClass, String text) {
		for (T e : enumClass.getEnumConstants()) {
			if (e.getText().equals(text)) {
				return e;
			}
		}
		return null;
	}

	public final static <T extends TextualEnum> T getByText(Class<T> enumClass, String text, T defaultValue) {
		for (T e : enumClass.getEnumConstants()) {
			if (e.getText().equals(text)) {
				return e;
			}
		}
		return defaultValue;
	}

	public final static <T extends Enum<T>> T get(Class<T> enumClass, String name, T defaultValue) {
		T e = Enum.valueOf(enumClass, name);
		if (null == e) {
			return defaultValue;
		}
		// for (Object o : enumClass.getEnumConstants()) {
		// NamedEnum e = (NamedEnum) o;
		// if (e.getName().equals(name)) {
		// return (T) e;
		// }
		// }
		return e;
	}

	public final static <T extends Enum<T>> T get(Class<T> enumClass, String name) {
		return get(enumClass, name, null);
	}

}
